package controllers

import (
	"gin-blog/config"
	"gin-blog/models"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type PostController struct{}

type CreatePostRequest struct {
	Title      string `json:"title" binding:"required"`
	Content    string `json:"content" binding:"required"`
	Summary    string `json:"summary"`
	CategoryID uint   `json:"category_id"`
	Tags       string `json:"tags"`
	Status     string `json:"status"`
}

type UpdatePostRequest struct {
	Title      string `json:"title"`
	Content    string `json:"content"`
	Summary    string `json:"summary"`
	CategoryID uint   `json:"category_id"`
	Tags       string `json:"tags"`
	Status     string `json:"status"`
}

// 获取文章列表
func (pc *PostController) GetPosts(c *gin.Context) {
	var posts []models.Post
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", "10"))
	status := c.Query("status")
	categoryID := c.Query("category_id")
	authorID := c.Query("author_id")

	offset := (page - 1) * limit

	query := config.DB.Preload("Author").Preload("Category")

	// 添加筛选条件
	if status != "" {
		query = query.Where("status = ?", status)
	}
	if categoryID != "" {
		query = query.Where("category_id = ?", categoryID)
	}
	if authorID != "" {
		query = query.Where("author_id = ?", authorID)
	}

	// 获取总数
	var total int
	query.Model(&models.Post{}).Count(&total)

	// 获取文章列表
	if err := query.Order("created_at DESC").Offset(offset).Limit(limit).Find(&posts).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch posts"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"posts": posts,
		"pagination": gin.H{
			"page":  page,
			"limit": limit,
			"total": total,
			"pages": (total + limit - 1) / limit,
		},
	})
}

// 获取单篇文章
func (pc *PostController) GetPost(c *gin.Context) {
	id := c.Param("id")
	var post models.Post

	if err := config.DB.Preload("Author").Preload("Category").Preload("Comments.Author").First(&post, id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Post not found"})
		return
	}

	// 增加浏览量
	config.DB.Model(&post).Update("view_count", post.ViewCount+1)

	c.JSON(http.StatusOK, gin.H{"post": post})
}

// 创建文章
func (pc *PostController) CreatePost(c *gin.Context) {
	var req CreatePostRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	userID, _ := c.Get("user_id")

	post := models.Post{
		Title:      req.Title,
		Content:    req.Content,
		Summary:    req.Summary,
		AuthorID:   userID.(uint),
		CategoryID: req.CategoryID,
		Tags:       req.Tags,
		Status:     req.Status,
	}

	if post.Status == "" {
		post.Status = "draft"
	}

	if err := config.DB.Create(&post).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create post"})
		return
	}

	// 预加载关联数据
	config.DB.Preload("Author").Preload("Category").First(&post, post.ID)

	c.JSON(http.StatusCreated, gin.H{
		"message": "Post created successfully",
		"post":    post,
	})
}

// 更新文章
func (pc *PostController) UpdatePost(c *gin.Context) {
	id := c.Param("id")
	var req UpdatePostRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	var post models.Post
	if err := config.DB.First(&post, id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Post not found"})
		return
	}

	// 检查权限（只有作者或管理员可以编辑）
	userID, _ := c.Get("user_id")
	role, _ := c.Get("role")
	if post.AuthorID != userID.(uint) && role != "admin" {
		c.JSON(http.StatusForbidden, gin.H{"error": "Permission denied"})
		return
	}

	// 更新字段
	if req.Title != "" {
		post.Title = req.Title
	}
	if req.Content != "" {
		post.Content = req.Content
	}
	if req.Summary != "" {
		post.Summary = req.Summary
	}
	if req.CategoryID != 0 {
		post.CategoryID = req.CategoryID
	}
	if req.Tags != "" {
		post.Tags = req.Tags
	}
	if req.Status != "" {
		post.Status = req.Status
	}

	if err := config.DB.Save(&post).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update post"})
		return
	}

	// 预加载关联数据
	config.DB.Preload("Author").Preload("Category").First(&post, post.ID)

	c.JSON(http.StatusOK, gin.H{
		"message": "Post updated successfully",
		"post":    post,
	})
}

// 删除文章
func (pc *PostController) DeletePost(c *gin.Context) {
	id := c.Param("id")
	var post models.Post

	if err := config.DB.First(&post, id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Post not found"})
		return
	}

	// 检查权限（只有作者或管理员可以删除）
	userID, _ := c.Get("user_id")
	role, _ := c.Get("role")
	if post.AuthorID != userID.(uint) && role != "admin" {
		c.JSON(http.StatusForbidden, gin.H{"error": "Permission denied"})
		return
	}

	if err := config.DB.Delete(&post).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete post"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Post deleted successfully"})
}

// 点赞文章
func (pc *PostController) LikePost(c *gin.Context) {
	id := c.Param("id")
	var post models.Post

	if err := config.DB.First(&post, id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Post not found"})
		return
	}

	// 增加点赞数
	if err := config.DB.Model(&post).Update("like_count", post.LikeCount+1).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to like post"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message":    "Post liked successfully",
		"like_count": post.LikeCount + 1,
	})
}
